/**
 * 
 */
package edu.sjtu.seda.experiment;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import edu.sjtu.seda.event.Event;
import edu.sjtu.seda.event.EventHandler;
import edu.sjtu.seda.log.LogService;
import edu.sjtu.seda.test.Message;
import edu.sjtu.seda.test.PrintMessage;
import edu.sjtu.seda.test.TransferMessage;
import edu.sjtu.seda.test.WriteToFile;

/**
 * @author john.zhu
 *
 */
public class ThreadPerRequestTest {
	
	protected static LogService log = new LogService(ThreadPerRequestTest.class);
	
	static class RunTest implements Runnable{
		private Event event;
		private EventHandler[] eventhandlers;
		
		public RunTest(Event event,EventHandler... eventhandlers){
			this.event = event;
			this.eventhandlers = eventhandlers;
		}
		
		public void run(){
			for(EventHandler handler : eventhandlers){
				log.info("event {0} is running",event.getUID());
				handler.handle(event);
				log.info("event {0} ended",event.getUID());
			}
		}
	}
	
	static class TestThread1 implements Runnable {

		private int i = 0;
        
		
		public TestThread1(int i){
			this.i = i;
		}
		
		@Override
		public void run() {
			Message m = new Message("Message "+i);
			log.info("event "+m.getUID()+" will start");
			Thread thread = new Thread(new RunTest(m,new TransferMessage(),new PrintMessage()));
			thread.start();
		}
	}
	
	static class TestThread2 implements Runnable {

		private int i = 0;


		public TestThread2(int i) {
			this.i = i;
		}

		@Override
		public void run() {
			Message m = new Message("Message " + i);
			log.info("event " + m.getUID() + " will start");
			Thread thread = new Thread(new RunTest(m,new WriteToFile(),new PrintMessage()));
			thread.start();
		}
	}
	
	public static void main(String[]args){
		long startNano = System.nanoTime();
//		SingleThreadPool tp = new SingleThreadPool(50);
		File file = new File("d://b.txt");
		FileWriter write = null;
		try {
			write = new FileWriter(file);
			write.write(new SimpleDateFormat("MM/dd/yy HH:mm:ss.SSS").format(new Date()));
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				write.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		for (int i = 0; i < 10000; i++) {
			if(i%2==0){
				Thread t1 = new Thread(new TestThread1(i));
				t1.start();
			}
			else{
				Thread t2 = new Thread(new TestThread2(i));
				t2.start();
			}
		}
		
	}

}
